// 云函数入口文件
const isNumber = require('lodash/isNumber')
const cloud = require('wx-server-sdk')
const appid = process.env.appid //你的小程序appid
const secret = process.env.secretkey //你的小程序secret

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const ERROR_MSG = {
    500: '服务器错误',
    401: '登录过期',
    404: '未找到资源',
    4001: '重复提交'
}
class CustomError extends Error {
    constructor(code, msg) {
        super()
        this.code = code || 500
        this.msg = msg || ERROR_MSG[code] || 'unknown error'
    }
    getCodeMsg() {
        return {
            code: this.code,
            msg: this.msg
        }
    }
}
// 增加额外command功能
const _ = db.command
// 1. 获取数据库引用
const TcbRouter = require('tcb-router')

exports.main = async (event, context) => {

    const app = new TcbRouter({ event })
    const { OPENID, UNIONID } = cloud.getWXContext()
    app.use(async (ctx, next) => {
        //适用于所有的路由
        ctx.data = {} //声明data为一个对象
        try {
            ctx.body = {}
            ctx.body.code = 0
            await next()
        } catch (err) {
            console.log(err, 'err'.repeat(10))
            console.log(ctx)
            if (err instanceof CustomError) {
                const res = err.getCodeMsg()
                ctx.body = {}
                ctx.body.code = res.code || 500
                ctx.body.msg = res.msg
            } else if (err instanceof Error) {
                console.log(err)
                ctx.body = {}
                ctx.body.code = 500
                ctx.body.msg = err.message
            } else if (typeof err === 'string') {
                ctx.body = {}
                ctx.body.code = 500
                ctx.body.msg = err
            } else {
                ctx.body = {}
                ctx.body.code = res.code || 500
                ctx.body.msg = res.msg
            }
        }
    })

    //向规划表里添加数据
    app.router('Update', async (ctx, next) => {
        const {
            author,
            data,
            reception_person
        } = event
        try {
            await db.collection("plan").add({
                data: {
                    author: author,
                    reception_person: reception_person,
                    morning: data.morning,
                    aft: data.aft,
                    night: data.night
                }
            }).then(res => {
                return res
            })
        } catch (error) {
            console.log(error)
        }
    })

    //从云函数中获取对应人员的营养规划
    app.router("oneSelf", async (ctx, next) => {
    // if (event.event === "oneSelf") {
        const { reception_person } = event
        try {
            await db.collection("plan").where({
                reception_person: reception_person
            }).get().then(res => {
                return ctx.body = {
                  data:res
                }
            })
        } catch (error) {
            return error
        }
    // }
    })
    return app.serve()
}